import { Input, message, Modal } from 'antd';
import { useEffect, useState } from 'react';
import './work.scss';
import { useNavigate } from 'react-router-dom';
import workbenchService from '@/api/services/workbenchService';
import { eventBus, EventNameEnum } from '@/utils/eventBus';
import orchestrationService from '@/api/services/orchestrationService';
import TipsModals from '../modals/TipsModals';
import Modals from '../modals/Modals';
import { AppStatusEnum, AppWorkbenchType } from '@/common/app/constants';
import useModal from '@/hooks/use-modal/useModal';
import { SvgIcon } from '../icon';
import { useUserInfo } from '@/store/userStore';

interface WorkDropdownProps {
  title: string;
  items: any;
  icon: string;
  onUpdateWork?: () => void;
}

export default function WorkDropdown({ title, items, icon, onUpdateWork }: WorkDropdownProps) {
  const [isShowDelete, setIsShowDelete] = useState(false);
  const [isShowCopy, setIsShowCopy] = useState(false);
  const [copyName, setCopyName] = useState('');
  const router = useNavigate();
  const [messageApi, contextHolder] = message.useMessage();

  const modal = useModal('update', 'personnel', 'delete', 'edit');
  const { username, role } = useUserInfo();

  const handleCancel = () => {
    onUpdateWork && onUpdateWork();

    setIsShowDelete(false);
    setIsShowCopy(false);
  };

  const changeDropdown = async (e: any) => {
    e.stopPropagation();
    if (title === '删除') {
      if (items.isSSO) {
        modal.delete.open();
      } else {
        setIsShowDelete(true);
      }
    } else if (title === '复制') {
      setIsShowCopy(true);
    } else {
      // 待审批中的应用，超管跳转审核页面
      if (items.review_status === AppStatusEnum.pending && role?.code === 'super_admin') {
        if (items.app_type === 'agent') {
          router(`/apps/viewOrchestration?appType=${items.app_type}&appId=${items.app_id}`);
        } else {
          router(
            `/apps/viewOrchestration?appType=${items.app_type}&appId=${items.app_id}&currentTab=preview`,
          );
        }
        return;
      }

      if (items.app_type === 'agent') {
        let res: any = '';
        if (items.share_id) {
          res = items;
        } else {
          res = await orchestrationService.getAppDetailV2(items.app_id, AppWorkbenchType.manage);
        }
        if (res.share_id) {
          router(`/apps/orchestration?appId=${items.app_id}&shareId=${res.share_id}`);
        } else {
          message.info('应用未发布，无法编辑');
        }
      } else if (items.app_type === 'workflow') {
        router(`/app/workflow?appId=${items.app_id}&shareId=${items.share_id}`);
      } else {
        router(`/apps/orchestration?appId=${items.app_id}&shareId=${items.share_id}`);
      }
    }
  };

  const handleOK = async () => {
    try {
      if (title === '删除') {
        setIsShowDelete(false);
        //确定发送请求
        await workbenchService.deleteWorkDataApi(items.app_id);
        message.success('删除成功');
      }
      if (title === '复制') {
        setIsShowCopy(false);
        await workbenchService.copyWorkDataApi({
          app_type: items.app_type,
          template_app_id: items.app_id,
          app_name: copyName,
        });
        message.success('复制成功');
      }
      onUpdateWork && onUpdateWork();
      //重新请求数据 (让用户看到最新的数据)
      eventBus.emit(EventNameEnum.addFlagText, {
        value: true,
      });
    } catch (error) {
      console.error('操作失败:', error);
      message.error(error);
    }
  };

  const changeCopyName = (e: any) => {
    e.stopPropagation();
    setCopyName(e.target.value);
    console.log(e.target.value);
  };

  return (
    <div>
      {contextHolder}
      <div
        onClick={(e) => changeDropdown(e)}
        style={title === '删除' ? { color: 'red' } : {}}
        className="flex h-[28px] w-[90px] items-center text-[13px] text-[#1D2129]"
      >
        <SvgIcon icon={icon} size={16} className="mr-2" />
        {title}
      </div>

      {/* 删除的弹框 */}
      <TipsModals
        okText="删除"
        centered
        open={isShowDelete}
        onOk={handleOK}
        onCancel={handleCancel}
      >
        <p>确定要删除应用【{items.app_name}】吗？</p>
      </TipsModals>

      {/* 删除的融合应用 */}
      <TipsModals
        okText="删除"
        centered
        open={modal.delete.isOpen}
        onOk={async () => {
          //确定发送请求
          await workbenchService.deleteWorkDataApi(items.app_id);
          message.success('删除成功');
          onUpdateWork && onUpdateWork();
          //重新请求数据 (让用户看到最新的数据)
          eventBus.emit(EventNameEnum.addFlagText, {
            value: true,
          });
          modal.delete.close();
        }}
        onCancel={modal.delete.close}
      >
        <p>应用已被用于登录页，若删除后续用户登录跳转为应用中心，确认删除？</p>
      </TipsModals>

      {/* 复制的弹框 */}
      <Modals title="复制应用" centered open={isShowCopy} onOk={handleOK} onCancel={handleCancel}>
        <div className="text">应用名称</div>
        <Input
          onChange={(e) => changeCopyName(e)}
          size="small"
          style={{ borderRadius: '6px', margin: '10px 0px', height: '40px' }}
        />
      </Modals>
    </div>
  );
}
